<?php
/**
 * @package   auto_occasion
 * @subpackage 
 * @author    CMS
 * @copyright 2011 
 * @license    All rights reserved
 */

require_once(LIB_PATH.'phpMailer/class.phpmailer.php');

class communSrv {

   
    /*
     * Transform a french date to mysql date according to the separator
     * ex : input 24/12/2011 => 2011-12-24
     *
     */
    public function toDateSql ($dateFr, $sep="/") {
        $date = explode($sep, $dateFr);
        if (sizeof($date) > 1 ) return $date[2]."-".$date[1]."-".$date[0];
        else return $dateFr;
    }

    /*
     * Transform a sql date to fr date according to the separator
     * ex : output 24/12/2011 <= 2011-12-24
     *
     */
    public function toDateFr ($dateSql, $sep="-") {
        $date = explode($sep, $dateSql);
        return $date[2]."/".$date[1]."/".$date[0];
    }

    /*
     * Return a radom string
     *
     */
    public static function radomString () {
        $tab = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "0", "1", "2", "3", "4", "5");
        $result = "";
        for ($i=0; $i<=8; $i++) {
            $random = array_rand($tab);
            $result .= $tab[$random];
        }
        return $result; 
    }

    /*
     * send a mail
     * @param object 
     *
     */
    public function sendMail ($datas) {
        $datas->pwd = self::radomString();
        jAuth::changePassword($datas->login, $datas->pwd);

        $tpl = new jTpl();
        $tpl->assign('datas', $datas);
        $contenu = $tpl->fetch('commun~mailRecuperationMdp');

        $mail = new PHPmailer();
        $mail->IsSMTP();
        $mail->IsHTML(true);
        $mail->AddAddress($datas->email);
        $mail->Host         = 'sd-32323.dedibox.fr';
        $mail->Username     = 'test';
        $mail->Password     = 'fzjd90vdj32';
        $mail->SMTPAuth		= true;
        $mail->From         = 'noreply@auto-occasion.fr';
        $mail->FromName     = 'Auto - occasion';
        $mail->Subject      = 'Vos identifiants de connexion';
        $mail->Body         = $contenu;
        
        if (!$mail->Send()){ //Teste si le return code est ok.
          echo $mail->ErrorInfo; //Affiche le message d'erreur
          die();
        }
        
        $mail->SmtpClose();
        unset($mail);
    }


    /**
     * Fonction permettant d'uploader une image sur le serveur
     * @param array $fileToUpload
     * @param array $path
     * @return string filename 
     *
     */
    public static function uploadImage ($fileToUpload, $path) {
        if ($fileToUpload['name']) {
            try {
                jClasses::inc('commun~uploader');

                $uploader = new uploader();
                $uploader->source  = $fileToUpload;
                $uploader->destDir = $path;
                $uploader->upload();

            } catch (exception $e) {
                die($e->getMessage());
            }
            
            return $fileToUpload['name'];
        }

        return null;
    }
    
    public static function deleteOldPhotos(){
        $cnx  = jDb::getConnection();
        $sql  = "SELECT IdOccasion FROM ao_voiture_occasion ";
        $sql .= "WHERE  (Occas_Valide = '2' or Occas_Valide = '3')";
        $sql .= "AND datediff(now(),Occas_DateModif)>60  AND Occas_AffPart != '1' ";
        $sql .= "AND (Occas_Option_Image <> '0' and Occas_Option_Image <> '')";
        $rs   = $cnx->query($sql);
        while ($row = $rs->fetch()){
        $imgpath = PHOTO_ILLUSTRATION_PATH.$row->IdOccasion."/";
            //check if dir is exist
            if(is_dir($imgpath)) {
                    if ($handle = opendir($imgpath)) { // open dir
                        while (false !== ($file = readdir($handle))) { //read dir object one by one
                            if ($file != "." && $file != "..") {
                               if(is_dir($imgpath.$file)) { // check if dir
                                    //call function to delete directory
                                    delete_dir($imgpath,$file); 
                               } else {
                                     //delete file
                                    unlink($imgpath.$file); 
                               }
                             }
                        }
                        rmdir($imgpath);
                    }
            }
        }
    }
    
    function delete_dir($path,$file) {
        $newpath = $path.$file."/";
        if(is_dir($newpath)) {
            if ($handle = opendir($newpath)) {
                        while (false !== ($file = readdir($handle))) {
                            if ($file != "." && $file != "..") {
                               if(is_dir($newpath.$file)) {
                                    //if its dir then call to recursive function delete_dir 
                                    delete_dir($newpath,$file);
                               } else {
                                    unlink($newpath.$file);
                               }
                            }
                        }
                        rmdir($newpath);
                   }
        }
    }
    
    /*
     * Fonction pour recuperer le temps en microsecondes
     */
    public static function getmicrotime(){
        list($usec, $sec) = explode(" ",microtime());
        return ((float)$usec + (float)$sec);
    }
    
    /*
     * @desc Affiche le temps écoulé (en microsecondes) depuis la dernière étape.
     * @param string $nom_etape  
     * 
     */
    public static function benchmark ($nom_etape)
    {
        global $etape_prec;
        $temps_ecoule = ($etape_prec) ? round((self::getmicrotime() - $etape_prec)*1000) : 0;
        $retour = '<p class="alerte">' . $nom_etape . ' : ' . $temps_ecoule . 'ms</p><br />';
        $etape_prec = self::getmicrotime();
        return $retour;
    }

}
